package com.faxsun.tools;

import java.text.DateFormat;
import java.util.Date;

import org.broadleafcommerce.openadmin.dto.Entity;
import org.broadleafcommerce.openadmin.dto.Property;

/**
 * Broaodleaf中Entity工具类
 * 
 * @author user
 *
 */
public class EntityHelper {

	/**
	 * 验证Broadleaf中的Entity是否为指定class的实例
	 * 
	 * @param entity
	 *            待验证实体
	 * @param clazz
	 *            目标class
	 * @return true，实体是目标class的实例；反之，false
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean isTargetClass(Entity entity, Class clazz) {
		boolean isInstance = true;
		Class entityClazz = null;
		try {
			entityClazz = Class.forName(entity.getType()[0]);
		} catch (Exception e) {
			e.printStackTrace();
			isInstance = false;
		}

		isInstance = isInstance && entityClazz != null
				&& clazz.isAssignableFrom(entityClazz);

		return isInstance;
	}

	/**
	 * 验证Broadleaf中的Class name是否为指定class的子类
	 * 
	 * @param entity
	 *            待验证实体
	 * @param clazz
	 *            目标class
	 * @return true，实体是目标class的实例；反之，false
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static boolean isTargetClass(String className, String clazzName) {
		boolean isInstance = true;
		Class entityClazz = null;
		Class clazz = null;
		try {
			entityClazz = Class.forName(className);
			clazz = Class.forName(clazzName);
		} catch (Exception e) {
			e.printStackTrace();
			isInstance = false;
		}

		isInstance = isInstance && entityClazz != null
				&& clazz.isAssignableFrom(entityClazz);

		return isInstance;
	}

	/**
	 * 从实体中获取指定的属性值
	 * 
	 * @param entity
	 *            实体
	 * @param name
	 *            属性名
	 * @return
	 */
	public static String getFieldFromProperties(Entity entity, String name) {

		Property p = entity.getPMap().get(name);
		return p.getValue();
	}

	/**
	 * 设置实体中的属性
	 * 
	 * @param entity
	 * @param name
	 * @param value
	 */
	public static void setFieldFromProperties(Entity entity, String name,
			String value) {
		if (entity == null || name == null || value == null || name.isEmpty()
				|| value.isEmpty()) {
			return;
		}
		Property p = entity.getPMap().get(name);
		p.setValue(value);
		entity.getPMap().put(name, p);
	}

	/**
	 * 获取当前时间，格式：2015-01-05 10:40:00
	 * 
	 * @return
	 */
	public static String getCurrentTime() {
		Date now = new Date();
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
				DateFormat.MEDIUM);
		return df.format(now);
	}
}
